package com.restful.auth;

import cn.hutool.core.util.IdUtil;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

/**
 * @author xiangminwen
 * @date 2024/12/23 14:16
 */
@Slf4j
@Component
@WebFilter(filterName = "commonFilter", urlPatterns = "/**")
public class CommonFilter implements Filter {

    public static final String TRACE_ID = "TRACE_ID";
    public static final String SPAN_ID = "SPAN_ID";

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter) throws IOException, ServletException {
        try {
            HttpServletRequest req = (HttpServletRequest) request;
            MDC.put(TRACE_ID, req.getHeader(TRACE_ID));
            MDC.put(SPAN_ID, IdUtil.objectId());
            filter.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }

    @Override
    public void destroy() {
        MDC.clear();
    }
}
